
import axios from 'axios'
import {
	Message,
	MessageBox
} from 'element-ui'
import {
	getToken,
	removeToken
} from '@/utils/auth'
import sessionStorage from '@/utils/session'

import router from '@/router'
import socketService from "@/socket/index.js";
import {confirmCconfig,imageNowIP} from "@/utils/config"
// 创建axios实例
const service = axios.create({
	baseURL:imageNowIP, // api的base_url
	timeout: 1200000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
	let token = getToken() || "";
	if (token != "" || token != undefined) {
		config.headers['Authorization'] = token ? "Bearer " + token : ""; // 让每个请求携带自定义token 请根据实际情况自行修改
	}
	return config
}, error => {
	// Do something with request error
	console.log(error) // for debug
	Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
	response => {
		/**
		 * code为非200是抛错 可结合自己业务进行修改
		 */
		const res = response.data;
		if (res.code === 401) {
			if (confirmCconfig.isTure) {
				confirmCconfig.isTure = false;
				removeToken();
				// sessionStorage.removeSession();
				socketService.socket.onclose();//关闭连接
				MessageBox.confirm('登录失效，可以取消继续留在该页面,或者重新登录', '提示', {
					confirmButtonText: '重新登录',
					cancelButtonText: '取消',
					type: 'warning'
				}).then((data) => {
					confirmCconfig.isTure = true;
					router.push('/login')
				}).catch(err=>{
					confirmCconfig.isTure = true;
				})
			}
			return Promise.reject('error')
		} else if (res.code !== 200) {
			Message({
				message: res.message || res.msg || res.data.message,
				type: 'error',
				duration: 3 * 1000
			})
			return Promise.reject('error')
		} else {
			return res
		}
	},
	error => {
		console.log('err' + error) // for debug
		Message({
			message: error.message,
			type: 'error',
			duration: 3 * 1000
		})
		return Promise.reject(error)
	}
)

export default service